package com.google.monkeyjump.db;

import java.util.ArrayList;
import java.util.List;

import util.Constants;
import android.content.Context;
import android.database.Cursor;

import com.google.monkeyjump.ranking.Rank;

public class DataBaseAdapter {

	private DataBaseHelper dataBaseHelper;
	
	private static DataBaseAdapter instance;

	private DataBaseAdapter(Context context) {
		this.dataBaseHelper = new DataBaseHelper(context);
	}
	
	public static DataBaseAdapter getInstance(Context context){
		if(instance == null){
			instance = new DataBaseAdapter(context);
		}
		
		return instance;
	}
	
	public static void destroy() {
		if(instance != null){
			instance.close();
		}
		instance = null;
	}
	
	private void close() {
		dataBaseHelper.close();
	}

	public void addRank(Rank rank){
		dataBaseHelper.insert(rank);
	}
	
	public List<Rank> getRanks(){
		Cursor ranksCursor = dataBaseHelper.getReadableDatabase().
				query(Constants.RANK_TABLE_NAME, null, null, null, null, null, 
				Constants.RANK_POINTS_COLUMN_NAME + "  DESC");
		
		List<Rank> ranks = getRanksFromCursor(ranksCursor);
		
		ranksCursor.close();
		
		return ranks;
	}
	
	private List<Rank> getRanksFromCursor(Cursor ranksCursor){
		List<Rank> ranks = new ArrayList<Rank>();

		int pointsColumnIndex = ranksCursor.getColumnIndex(
				Constants.RANK_POINTS_COLUMN_NAME);
		int userColumnIndex = ranksCursor.getColumnIndex(
				Constants.RANK_USER_COLUMN_NAME);
		
		while(ranksCursor.moveToNext()){
			Rank rank = new Rank();
			rank.setPoints(ranksCursor.getLong(pointsColumnIndex));
			rank.setUser(ranksCursor.getString(userColumnIndex));
			ranks.add(rank);
		}
		
		return ranks;
	}

	public static DataBaseAdapter getInstance() {
		return instance;
	}
	
}
